package com.bdqn.day0919.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bdqn.day0919.entity.User;
import com.bdqn.day0919.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:Corday
 * @Date:2021/09/19/10:03
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService us;

    ////restful风格的映射////
// 对应有匹配的动作,跟前端请求动作一致
// get查询/post添加/ put修改/delete删除
//如果没有使用restful风格，则前端的get与post都能实现curd
//    1.删除一条记录
    @DeleteMapping("/{uid}")
    @CrossOrigin//允许前端ajax请求
    public JSONObject del(@PathVariable("uid") Integer uid) {
        //String info=us.removeUser(uid);
        //"'info':'删除10086'"
        String text = "{'info':" + "'删除" + uid + "'}";
        JSONObject obj = JSON.parseObject(text);
        return obj;
    }

    //    2.更新一条记录
    @PutMapping("/{uid}/{sex}")
    @CrossOrigin
    //@RequestMapping(value = "/{uid}/{sex}",method = RequestMethod.PUT)
    public String update(@PathVariable Integer uid, @PathVariable String sex) {
        us.saveUser(new User("小丽", "女"));
        return "更新：用户名:" + uid + " 性别:" + sex;
    }

    //    3.插入一条记录
    @PostMapping("/insert")
    @CrossOrigin
    public String insert() {
        //拿到自动生成的uid
        User u=new User("李好","女");
        us.saveUser(u);
        //插入完成后会将自增的uid反填回user对象
        return "uid:"+u.getUid();
    }

    //    插入多条记录
    @PostMapping("/users")
    @CrossOrigin//此处允许前端ajax请求操作
    public String insertUsers() {
        List<User> users = new ArrayList<>();//模拟添加多条记录
        users.add(new User("小明", "男"));
        users.add(new User("小江", "男"));
        users.add(new User("美丽", "女"));
        return us.saveUsers(users);
    }

    //    4.查询一条记录
    @GetMapping("/")
    @CrossOrigin
    public List<User> getUsers() {
        return us.findUsers();
    }

}
